from django.shortcuts import render
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse
from employee.models import employee,casedata,bugdata
# 分页需要导的包
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
# 聚合函数
from django.db.models import Max,Min,Sum,Count

# 判空的方法
def is_empty(n):
    return n is None or str(n).strip() == ''
# 注册
@api_view(['post'])
def register(request):
    # 解析请求中的数据
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    gender = data.get('gender')
    age = data.get('age')
    department = data.get('department')
    kpi = data.get('kpi')
    address = data.get('address')
    if is_empty(address):
        employee(name=name, password=password, gender=gender, age=age,
                 department=department, kpi=kpi).save()
    else:
        employee(name=name, password=password, gender=gender, age=age,
                 department=department, kpi=kpi, address=address).save()

    return JsonResponse({
        'code': 200,
        'msg': '添加成功'
    })


import logging


# 分页(列表展示)
@api_view(['get'])
def getinfo(request):
    # 鉴权代码
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({'msg':'未登录，请先登录','code':401})

    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    # name=request.GET.get('name')
    # gender=request.GET.get('gender')
    # department=request.GET.get('department')
    # address=request.GET.get('address')
    # if is_empty(name) and is_empty(gender) is False and is_empty(department) is False and is_empty(address) is False:
    #     allobj=employee.objects.filter(gender=gender,department=department,address=address)
    # elif is_empty(name) is False:
    #     allobj = employee.objects.filter(name=name)
    # elif is_empty(name) and is_empty(gender) and is_empty(department) is False and is_empty(address) is False:
    #     allobj = employee.objects.filter(gender=gender)
    # elif is_empty(name) and is_empty(gender) is False and is_empty(department) and is_empty(address) is False:
    #     allobj = employee.objects.filter(department=department)
    # elif is_empty(name) and is_empty(gender) is False and is_empty(department) is False and is_empty(address):
    #     allobj = employee.objects.filter(address=address)
    # elif is_empty(name) and is_empty(gender) and is_empty(department) and is_empty(address):
    #     allobj = employee.objects.filter()
    # else:
    #     allobj = employee.objects.filter()
    # 查询所有数据对象
    allobj = employee.objects.filter()
    logging.info(f'查看得到的数据对象:{allobj}')
    # 对所有数据进行分页，第一个参数是所有数据对象，第二个参数是每页有几个数据
    allpageobj = Paginator(allobj, pagesize)
    try:
        singleobj = allpageobj.page(page)
    except PageNotAnInteger:
        singleobj = allpageobj.page(1)
    except EmptyPage:
        singleobj = allpageobj.page(allpageobj.num_pages)

    logging.info(f'查看单页的数据对象:{singleobj}')

    # 定义空列表,存储数据
    lis = []
    logging.info(f'查看单页的数据对象object_list:{singleobj.object_list}')
    for i in singleobj.object_list:
        lis.append({
            'id': i.id,
            'name': i.name,
            'gender': '男' if i.gender=='M' else '女',
            'age': i.age,
            'department': i.department,
            'kpi': i.kpi,
            'address': i.address,
            'create_time': i.createtime,
            'update_time': i.updatetime

        })
    return JsonResponse({
        'code': 200,
        'data': lis,
        'pageinfo': {
            'page': page,
            'pagesize': pagesize
        },
        'items':allobj.count()
    })


# 鉴权
import random, string
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta


# 创建token（普通方法）
def createtoken(name):
    # 产生8位随机字符串
    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    # 对字符串进行签名
    token = Signer().sign(randomstr + name)
    # 把token保存到缓存中
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    return token


# 鉴权的方法
def checktoken(request):
    # 获取前端传过来的token
    reqtoken = request.META.get('HTTP_TOKEN')
    logging.info(f'查看前端传过来的token值:{reqtoken}')
    # 如果前端没有传token，返回False
    if reqtoken is None:
        return False, 'xxxx'
    # 先做一个反签名
    untoken = Signer().unsign(reqtoken)
    logging.info(f'查看反签名后的内容{untoken}')
    name = untoken[8:]
    # 校验缓存中的token是否存在
    cachetoken = cache.get(f'test_{name}')
    logging.info(f'查看缓存中的token内容:{cachetoken}')
    if cachetoken is None:
        return False, 'xxxx'
    return True, name


# 登录的方法
@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    # 判断用户存不存在
    is_exist = employee.objects.filter(name=name).exists()
    logging.info(f'查看是否存在的返回值:{is_exist}')
    if employee.objects.filter(name=name).exists() is False:
        return JsonResponse({'msg': '用户不存在','code':409})
    # 得到数据对象
    obj = employee.objects.get(name=name)
    logging.info(f'查看单个数据对象:{obj}')
    if obj.password != password:
        return JsonResponse({'msg': '密码错误','code':409})

    # 调用产生token的方法
    token = createtoken(name)
    return JsonResponse({
        'code': 200,
        'msg': '登录成功',
        'token': token
    })


# 分组查询
@api_view(['GET'])
def gruopdata(request):
    #接收分组后的数据
    data=employee.objects.values('gender').annotate(num=Count('gender'),minage=Min('age'),maxage=Max('age'),sumkpi=Sum('kpi'))
    logging.info(f'查看得到的数据：{data}')
    lis=[]
    for item in data:
        lis.append({
            # 三目运算符
            '性别':'男' if item.get('gender')=='M' else '女',
            '人数':item.get('num'),
            '最小年龄':item.get('minage'),
            '最大年龄':item.get('maxage'),
            'kpi之和':item.get('sumkpi'),
        })
    return JsonResponse({
        'code':200,
        'data':lis
    })

# 关联查询的方法
@api_view(['GET'])
def getbuginfo(request):
    bugobj=bugdata.objects.filter()
    lis=[]
    for item in bugobj:
        lis.append({
            '缺陷id':item.id,
            '缺陷标题':item.title,
            '缺陷状态':item.status,
            '实际结果':item.actual,
            '当前责任人':item.assigned,
            '用例名称':item.case.casename,
            '用例状态':item.case.status,
            '用例预期结果':item.case.expect
        })
    return JsonResponse({
        'code':200,
        'data':lis
    })

@api_view(['GET'])
def getcaseinfo(request):
    caseobj=casedata.objects.filter()
    lis=[]
    for item in caseobj:
        for items in item.bugdata.all():
            lis.append({
                '用例名称': item.casename,
                '用例状态': item.status,
                '用例预期结果': item.expect,
                '缺陷id':items.id,
                '缺陷标题':items.title,
                '缺陷状态':items.status,
                '实际结果':items.actual,
                '当前责任人':items.assigned

            })
    return JsonResponse({
        'code':200,
        'data':lis
    })

# 添加用例方法
@api_view(['POST'])
def addcase(request):

    # 鉴权
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg':'未登录，添加用例失败'
        },status=401)
    employeeobj=employee.objects.get(name=name)
    data=JSONParser().parse(request)
    casename=data.get('casename')
    status=data.get('status')
    step=data.get('step')
    expect=data.get('expect')
    # 非空判断
    if is_empty(casename) or is_empty(expect):
        return JsonResponse({
            'msg': '必填参数不能为空'
        }, status=400)
    # 判重
    if casedata.objects.filter(casename=casename).exists() is True:
        return JsonResponse({
            'msg': '用例已存在'
        }, status=409)
    casedata(casename=casename,status=status,step=step,expect=expect,employee=employeeobj).save()
    return JsonResponse({
        'code':200,
        'msg':'添加用例成功'
    })

# 关联查询
@api_view(['GET'])
def getcasebyemployee(request):
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'msg': '未登录，查看用例失败'
        }, status=401)
    employeeobj=employee.objects.get(name=name)
    lis=[]
    # 得到所有的用例对象
    allcaseobj=employeeobj.casedata.all()

    for item in allcaseobj:
        lis.append({
            '提交人':employeeobj.name,
            '用例名称':item.casename,
            '用例状态':item.status,
            '用例预期结果':item.expect
        })
    return JsonResponse({
        'code':200,
        'data':lis
    })

# 删除
@api_view(['DELETE'])
def deleteitem(request,itemid):
    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({'code':401,'msg':'未登录，无法删除数据'})
    employeeobj=employee.objects.get(id=itemid)

    employeeobj.delete()
    return JsonResponse({
        'code':200,
        'msg':'删除成功'
    })

#填充
@api_view(['get'])
def getiteminfo(request,itemid):

    # 查询所有数据对象
    item = employee.objects.get(id=itemid)
    return JsonResponse({
        'name': item.name,
        'gender': '男' if item.gender == 'M' else '女',
        'age': item.age,
        'department': item.department,
        'kpi': item.kpi,
        'address': item.address
    })

# 修改
@api_view(['PUT'])
def updateemployee(request,itemid):
    data=JSONParser().parse(request)
    age=data.get('age')
    gender=data.get('gender')
    department=data.get('department')
    kpi=data.get('kpi')
    address=data.get('address')
    # 查询所有数据对象
    item = employee.objects.get(id=itemid)

    item.gender=gender
    item.age=age
    item.department=department
    item.kpi=kpi
    item.address=address
    item.save()
    return JsonResponse({
        'code':200,
        'msg':'修改成功'
    })


# 搜索
@api_view(['GET'])
def searchinfo(request,itemid):
    # 查询所有数据对象
    allobj = employee.objects.filter(name=itemid)
    # 定义空列表,存储数据
    lis = []
    for item in allobj:
        lis.append({
            'id': item.id,
            'name': item.name,
            'gender': '男' if item.gender == 'M' else '女',
            'age': item.age,
            'department': item.department,
            'kpi': item.kpi,
            'address': item.address,
            'create_time': item.createtime,
            'update_time': item.updatetime

        })
    return JsonResponse({
        'code': 200,
        'data': lis,
        'items': allobj.count()
    })

# 多条件查询
@api_view(['GET'])
def searchinfo2(request):
    #获取用户名
    name=request.GET.get('name')
    sex=request.GET.get('sex')
    department=request.GET.get('department')
    if sex=='男':
        sex='M'
    elif sex=='女':
        sex='F'
    # 获取页码
    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    dic={}
    if is_empty(name) is False:
        dic['name__contains']=name

    if is_empty(name) is False:
        dic['gender'] = sex

    if is_empty(name) is False:
        dic['department'] = department
    allobj=employee.objects.filter(**dic)

    logging.info(f'查看得到的数据对象:{allobj}')
    # 对所有数据进行分页，第一个参数是所有数据对象，第二个参数是每页有几个数据
    allpageobj = Paginator(allobj, pagesize)
    try:
        singleobj = allpageobj.page(page)
    except PageNotAnInteger:
        singleobj = allpageobj.page(1)
    except EmptyPage:
        singleobj = allpageobj.page(allpageobj.num_pages)

    logging.info(f'查看单页的数据对象:{singleobj}')

    # 定义空列表,存储数据
    lis = []
    logging.info(f'查看单页的数据对象object_list:{singleobj.object_list}')
    for i in singleobj.object_list:
        lis.append({
            'id': i.id,
            'name': i.name,
            'gender': '男' if i.gender == 'M' else '女',
            'age': i.age,
            'department': i.department,
            'kpi': i.kpi,
            'address': i.address,
            'create_time': i.createtime,
            'update_time': i.updatetime

        })
    return JsonResponse({
        'code': 200,
        'data': lis,
        'pageinfo': {
            'page': page,
            'pagesize': pagesize
        },
        'items': allobj.count()
    })


# 动态获取后端jango数据
@api_view(['GET'])
def getdepartments(request):
    departments=employee.objects.values('department').annotate(itemid=Max('id'))
    logging.info(f'查看分组后的数据：{departments}')

    lis=[{'value': '', 'label': '请选择'}]
    for item in departments:
        lis.append({
            'value':item.get('department'),
            'label':item.get('department')
        })
    return JsonResponse({
        'code':200,
        'data':lis
    })







